using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.Drawing;
using THSLib;
using THSERP.BaseProvider;
using THSERP.BusinessEntities;
namespace THSERP.Modules.SaleReturn
{
    public class SaleReturnModule : BaseModuleERP
    {
        #region Constants
        public const String cstSaleReturnStatusNew = "New";
        public const String cstSaleReturnStatusComplete = "Complete";

        public const String cstSaleReturnTypeManual = "Manual";
        public const String cstSaleReturnTypeFromReceipt = "FromReceipt";

        public const String cstModuleActionComplete = "Complete";
        public const String cstModuleActionNone = "None";
        #endregion

        private SimpleButton AcceptPaymentButton;
        private guiCustomersInfo CustomerInfoForm;
        public String ModuleAction = SaleReturnModule.cstModuleActionNone;

        public SaleReturnModule()
        {
            Name = "SaleReturn";
            CurrentModuleEntity = new SaleReturnEntities();
            CurrentModuleEntity.Module = this;
            InitializeModule();

            THSLookupEdit lke = (THSLookupEdit)Controls["fld_lkeFK_ARPriceLevelID"];
            lke.CloseUp += new DevExpress.XtraEditors.Controls.CloseUpEventHandler(ChangePriceLevel);
            lke = (THSLookupEdit)Controls["fld_lkeFK_ARCustomerID"];
            lke.CloseUp += new DevExpress.XtraEditors.Controls.CloseUpEventHandler(ChangeCustomer);

            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)CurrentModuleEntity.MainObject;
            //Disable lookupedit if user is an employee
            if (THSApp.CurrentUsersInfo.FK_HREmployeeID > 0)
            {
                objSaleReturnsInfo.FK_HREmployeeID = THSApp.CurrentUsersInfo.FK_HREmployeeID;
                foreach (Control ctrl in Controls.Values)
                    if (!String.IsNullOrEmpty(ctrl.AccessibleName) && ctrl.AccessibleName.Contains("FK_HREmployeeID"))
                    {
                        (ctrl as THSLookupEdit).EditValue = THSApp.CurrentUsersInfo.FK_HREmployeeID;
                        ctrl.Enabled = false;
                    }

                //Show picture
                HREmployeesInfo objHREmployeesInfo = (HREmployeesInfo)new HREmployeesController().GetObjectByID(Convert.ToInt32(THSApp.CurrentUsersInfo.FK_HREmployeeID));
                if (objHREmployeesInfo != null)
                {
                    objSaleReturnsInfo.ARSaleReturnEmployeePicture = objHREmployeesInfo.HREmployeePicture;
                    CurrentModuleEntity.UpdateMainObjectBindingSource();
                }
            }
        
            AcceptPaymentButton = (SimpleButton)Controls["fld_btnAcceptPayment"];
            DisplayLabelText(objSaleReturnsInfo);
        }

        #region Local
        public override void ActionEdit()
        {
            if (((ARSaleReturnsInfo)CurrentModuleEntity.MainObject).ARSaleReturnStatus.Contains(SaleReturnModule.cstSaleReturnStatusComplete))
            {
                MessageBox.Show("The sale return has been completed and can not modify.", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Information);
                DevExpress.XtraBars.BarButtonItem barbtnEdit = ParentScreen.GetToolbarButton(BaseToolbar.ToolbarButtonEdit);
                if (barbtnEdit != null)
                    barbtnEdit.Down = false;
                CurrentModuleEntity.SetPropertyChangeEventLock(false);
                return;
            }
            base.ActionEdit();
        }

        public override void ActionNew()
        {
            base.ActionNew();
            //Disable lookupedit if user is an employee
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)CurrentModuleEntity.MainObject;
            if (THSApp.CurrentUsersInfo.FK_HREmployeeID > 0)
            {
                objSaleReturnsInfo.FK_HREmployeeID = THSApp.CurrentUsersInfo.FK_HREmployeeID;
                //Show employee picture
                HREmployeesInfo objHREmployeesInfo = (HREmployeesInfo)new HREmployeesController().GetObjectByID(objSaleReturnsInfo.FK_HREmployeeID);
                if (objHREmployeesInfo != null)
                {
                    ((ARSaleReturnsInfo)CurrentModuleEntity.MainObject).ARSaleReturnEmployeePicture = objHREmployeesInfo.HREmployeePicture;
                    CurrentModuleEntity.UpdateMainObjectBindingSource();
                }
            }

            objSaleReturnsInfo.FK_ICStockID = THSApp.CurrentCompanyInfo.FK_ICStockID;
            objSaleReturnsInfo.ARSaleReturnTypeCombo = SaleReturnModule.cstSaleReturnTypeManual;
            objSaleReturnsInfo.ARSaleReturnDate = DateTime.Now;
            objSaleReturnsInfo.FK_ARPriceLevelID = 1;
            objSaleReturnsInfo.ARSaleReturnStatus = SaleReturnModule.cstSaleReturnStatusNew;
            CurrentModuleEntity.UpdateMainObjectBindingSource();
            DisplayLabelText(objSaleReturnsInfo);
        }

        public override void ActionCancel()
        {
            base.ActionCancel();

            AcceptPaymentButton.Tag = "Discard";
            AcceptPayment();
            EnableFieldGroupControls(THSERPScreen.cstFieldGroupAction, false);
        }

        public override void ActionDelete()
        {
            base.ActionDelete();

            AcceptPaymentButton.Tag = "Discard";
            AcceptPayment();
            EnableFieldGroupControls(THSERPScreen.cstFieldGroupAction, false);
        }

        public void ActionRefundFromPOS()
        {
            if (Toolbar.IsNullOrNoneAction())
                ActionNew();
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)CurrentModuleEntity.MainObject;
            objSaleReturnsInfo.ARSaleReturnTypeCombo = SaleReturnModule.cstSaleReturnTypeFromReceipt;
            
            guiSelectPOS guiSelectPOS = new guiSelectPOS();
            guiSelectPOS.Module = this;
            guiSelectPOS.ShowDialog();
            if (guiSelectPOS.DialogResult == DialogResult.OK)
            {
                SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
                ICProductsController objProductsController = new ICProductsController();
                foreach (ARInvoiceItemsInfo objInvoiceItemsInfo in entity.ARReferenceInvoiceItemsList)
                {
                    ARSaleReturnItemsInfo objSaleReturnItemsInfo = new ARSaleReturnItemsInfo();
                    THSUtil.CopyObjectItems(objInvoiceItemsInfo, objSaleReturnItemsInfo, SaleReturnEntities.strARSaleReturnObjectName);
                    objSaleReturnItemsInfo.FK_ARInvoiceID = objInvoiceItemsInfo.FK_ARInvoiceID;
                    objSaleReturnItemsInfo.FK_ARInvoiceItemID = objInvoiceItemsInfo.ARInvoiceItemID;
                    objSaleReturnItemsInfo.FK_ICStockID = objSaleReturnsInfo.FK_ICStockID;
                    //Set item's picture
                    ICProductsInfo objProductsInfo = (ICProductsInfo)objProductsController.GetObjectByID(objSaleReturnItemsInfo.FK_ICProductID);
                    objSaleReturnItemsInfo.ARSaleReturnItemProductPicture = objProductsInfo.ICProductPicture;

                    SaleReturnItemsEntity entItem = new SaleReturnItemsEntity();
                    entItem.GetFromBusinessObject(objSaleReturnItemsInfo);
                    entity.ARSaleReturnItemsList.Add(entItem);
                }
                entity.UpdateTotalAmount();
                entity.ARSaleReturnItemsList.GridControl.InvalidateLookupEditColumns();
                entity.ARSaleReturnItemsList.GridControl.RefreshDataSource();
                if (entity.ARSaleReturnItemsList.Count > 0)
                    entity.ARSaleReturnItemsList.GridViewFocusRow(entity.ARSaleReturnItemsList.Count - 1);
            }
        }

        public override void SetDefaultValuesFromCustomer()
        {
            
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)entity.MainObject;

            int customerID = Convert.ToInt32(THSDbUtil.GetPropertyValue(entity.MainObject, "FK_ARCustomerID"));
            ARCustomersController objCustomersController = new ARCustomersController();
            ARCustomersInfo objCustomersInfo = (ARCustomersInfo)objCustomersController.GetObjectByID(customerID);
            if (objCustomersInfo != null)
            {
                //Set total amount, discount, price level for customer_Hieu.nguyen_30/3/2010
                ARPriceLevelsController objPriceLevelsController = new ARPriceLevelsController();
                ARPriceLevelsInfo objPriceLevelsInfo = (ARPriceLevelsInfo)objPriceLevelsController.GetObjectByID(objCustomersInfo.FK_ARPriceLevelID);
                objCustomersInfo.ARCustomerPriceLevelName = objPriceLevelsInfo.ARPriceLevelName;
                objCustomersInfo.ARCustomerTotalPurchase = objCustomersController.GetTotalInvoiceAmount(objCustomersInfo.ARCustomerID);
                objCustomersInfo.ARCustomerTotalDiscount = objCustomersController.GetTotalInvoiceDiscount(objCustomersInfo.ARCustomerID);
                objCustomersInfo.ARCustomerTotalRefund = objCustomersController.GetTotalInvoiceRefund(objCustomersInfo.ARCustomerID);

                if (!Toolbar.IsNullOrNoneAction())
                {
                    if (objCustomersInfo.FK_ARPriceLevelID > 0 && objCustomersInfo.FK_ARPriceLevelID != objSaleReturnsInfo.FK_ARPriceLevelID)
                        ShowCustomerInfo(objCustomersInfo, true);
                    else
                        ShowCustomerInfo(objCustomersInfo, false);
                    ((SaleReturnEntities)CurrentModuleEntity).SetDefaultValuesFromCustomer(objCustomersInfo, CustomerInfoForm.fld_chkApplyPriceLevel.Checked);
                }
                else
                    ShowCustomerInfo(objCustomersInfo, false);
            }
        }

        public void ShowCustomerInfo(ARCustomersInfo objCustomersInfo, bool showPriceLevelPanel)
        {
            if (CustomerInfoForm == null)
            {
                CustomerInfoForm = new guiCustomersInfo();
                CustomerInfoForm.Module = this;
            }
            CustomerInfoForm.DisplayCustomerInfo(objCustomersInfo);
            CustomerInfoForm.fld_chkApplyPriceLevel.Checked = false;
            CustomerInfoForm.fld_pnlPriceLevel.Visible = showPriceLevelPanel;
            CustomerInfoForm.ShowDialog();
        }

        public void AddItemToSaleReturnItemsList()
        {
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            ARSaleReturnItemsInfo objSaleReturnItemsInfo = (ARSaleReturnItemsInfo)entity.ModuleObjects[SaleReturnEntities.strARSaleReturnItemsObjectName];
            if (objSaleReturnItemsInfo.FK_ICProductID > 0)
            {
                entity.SetProductPriceByProductUnitPrice();
                entity.ARSaleReturnItemsList.AddObjectToList();
                entity.UpdateTotalAmount();
            }
        }

        public void ChangeItemFromSaleReturnItemsList()
        {
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            //ARSaleReturnItemsInfo objSaleReturnItemsInfo = (ARSaleReturnItemsInfo)entity.ModuleObjects[SaleReturnEntities.strARSaleReturnItemsObjectName];
            
            entity.SetProductPriceByProductUnitPrice();
            entity.ARSaleReturnItemsList.ChangeObjectFromList();
            entity.UpdateTotalAmount();
        }

        public void DeleteItemFromSaleReturnItemsList()
        {
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            entity.ARSaleReturnItemsList.RemoveSelectedRowObjectFromList();
            entity.UpdateTotalAmount();
        }

        public void ChangeCustomer(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                THSLookupEdit lke = (THSLookupEdit)sender;
                if (e.Value != lke.OldEditValue)
                {
                    SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
                    ((ARSaleReturnsInfo)entity.MainObject).FK_ARCustomerID = Convert.ToInt32(e.Value);
                    SetDefaultValuesFromCustomer();
                }
            }
        }

        public void ChangePriceLevel(object sender, DevExpress.XtraEditors.Controls.CloseUpEventArgs e)
        {
            if (!Toolbar.IsNullOrNoneAction())
            {
                DevExpress.XtraEditors.LookUpEdit lke = (DevExpress.XtraEditors.LookUpEdit)sender;
                if (e.Value != lke.OldEditValue)
                {
                    SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
                    ((ARSaleReturnsInfo)entity.MainObject).FK_ARPriceLevelID = Convert.ToInt32(lke.EditValue);
                    if (entity.ARSaleReturnItemsList.Count > 0)
                    {
                        if (MessageBox.Show("Do you want to update new price level to the listed items?", "#Message#", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            foreach (SaleReturnItemsEntity entItem in entity.ARSaleReturnItemsList)
                                entity.SetProductPrice(entItem, SaleReturnEntities.strARSaleReturnItemsObjectName);
                            entity.ARSaleReturnItemsList.GridControl.RefreshDataSource();
                            entity.UpdateTotalAmount();
                        }
                    }
                }
            }
        }

        public void ChangeDiscountPercent()
        {
            ((SaleReturnEntities)CurrentModuleEntity).UpdateTotalAmount();
        }

        public void ChangeDiscountAmount()
        {
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)entity.MainObject;
            if (objSaleReturnsInfo.ARSaleReturnSubTotalAmount > 0)
                objSaleReturnsInfo.ARSaleReturnDiscountPerCent = objSaleReturnsInfo.ARSaleReturnDiscountFix / objSaleReturnsInfo.ARSaleReturnSubTotalAmount * 100;
            entity.UpdateTotalAmount();
        }

        public void TakePayment()
        {
            if (Toolbar.IsNullOrNoneAction() && Toolbar.CurrentObjectID > 0)
            {
                ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)CurrentModuleEntity.MainObject;
                if (objSaleReturnsInfo.ARSaleReturnStatus == SaleReturnModule.cstSaleReturnStatusComplete)
                {
                    MessageBox.Show("Can not refund payment on complete goods refund.", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    return;
                }
                if (objSaleReturnsInfo.ARSaleReturnTotalAmount > 0)
                {
                    guiRefundDetails guiRefundDetails = new guiRefundDetails(objSaleReturnsInfo.ARSaleReturnTotalAmount, objSaleReturnsInfo.ARSaleReturnTotalAmount);
                    guiRefundDetails.Module = this;
                    if (guiRefundDetails.ShowDialog() == DialogResult.OK)
                    {
                        ((SaleReturnEntities)CurrentModuleEntity).ARDocumentPaymentDetailsList = guiRefundDetails.PaymentList;
                        ActionComplete();
                    }
                }
            }
        }

        public override int ActionSave()
        {
            int objectID = base.ActionSave();
            if (objectID > 0)
            {
                AcceptPaymentButton.Tag = "Discard";
                AcceptPayment();
                EnableFieldGroupControls(THSERPScreen.cstFieldGroupAction, false);
            }
            return objectID;
        }

        public override bool ActionComplete()
        {
            ModuleAction = SaleReturnModule.cstModuleActionComplete;
            bool complete = false;
            int objectID = ActionSave();
            if (objectID > 0)
            {
                if (base.ActionComplete())
                {
                    MessageBox.Show("Complete successfully.", "#Message#", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    complete = true;
                }
            }
            ModuleAction = SaleReturnModule.cstModuleActionNone;
            return complete;
        }

        public bool ActionCompletePrint()
        {
            if (ActionComplete())
            {
                PrintRefund();
                return true;
            }
            return false;
        }

        public override void Invalidate(int iObjectID)
        {
            base.Invalidate(iObjectID);

            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)entity.MainObject;
            //set picture
            HREmployeesInfo objHREmployeesInfo = (HREmployeesInfo)new HREmployeesController().GetObjectByID(objSaleReturnsInfo.FK_HREmployeeID);
            if (objHREmployeesInfo != null)
            {
                ((ARSaleReturnsInfo)CurrentModuleEntity.MainObject).ARSaleReturnEmployeePicture = objHREmployeesInfo.HREmployeePicture;
                CurrentModuleEntity.UpdateMainObjectBindingSource();
            }

            objSaleReturnsInfo.ARSaleReturnChangeAmount = 0;
            foreach (ARDocumentPaymentDetailsInfo objDocumentPaymentDetailsInfo in entity.ARDocumentPaymentDetailsList)
                objSaleReturnsInfo.ARSaleReturnChangeAmount += objDocumentPaymentDetailsInfo.ARDocumentPaymentDetailAmount;
            objSaleReturnsInfo.ARSaleReturnChangeAmount = Math.Abs(objSaleReturnsInfo.ARSaleReturnChangeAmount);
            objSaleReturnsInfo.ARSaleReturnReceivingAmount = 0;
            if (objSaleReturnsInfo.ARSaleReturnChangeAmount >= objSaleReturnsInfo.ARSaleReturnTotalAmount)
                objSaleReturnsInfo.ARSaleReturnReceivingAmount = objSaleReturnsInfo.ARSaleReturnChangeAmount - objSaleReturnsInfo.ARSaleReturnTotalAmount;
            DisplayLabelText(objSaleReturnsInfo);
        }

        public void AcceptPayment()
        {
            SaleReturnEntities entity = (SaleReturnEntities)CurrentModuleEntity;
            ARSaleReturnsInfo objSaleReturnsInfo = (ARSaleReturnsInfo)entity.MainObject;
            if (AcceptPaymentButton.Tag.ToString() == "Accept")
            {
                double refundAmount = 0;
                if (CustomerPayment.CustomerPaymentModule.AcceptRefund(entity.ARDocumentPaymentDetailsList, objSaleReturnsInfo.ARSaleReturnTotalAmount, ref refundAmount))
                {
                    AcceptPaymentButton.Text = "Discard Payment";
                    AcceptPaymentButton.Tag = "Discard";
                    EnableFieldGroupControls("Accept", false);
                    EnableFieldGroupControls("Discard", true);
                    objSaleReturnsInfo.ARSaleReturnReceivingAmount = refundAmount - objSaleReturnsInfo.ARSaleReturnTotalAmount;
                    objSaleReturnsInfo.ARSaleReturnChangeAmount = refundAmount;
                    DisplayLabelText(objSaleReturnsInfo);
                }
            }
            else
            {
                AcceptPaymentButton.Text = "Accept Payment";
                AcceptPaymentButton.Tag = "Accept";
                EnableFieldGroupControls("Accept", true);
                EnableFieldGroupControls("Discard", false);
            }
        }

        /// <summary>
        /// Print refund
        /// </summary>
        /// <remarks>Hieu.nguyen_09/04/2010</remarks>
        public void PrintRefund()
        {
            if (Toolbar.CurrentObjectID > 0)
            {
                String reportFileName = "Refund.rpt";
                String strReportFileName = System.Windows.Forms.Application.StartupPath + "\\Reports\\" + this.Name + "\\" + reportFileName;
                ReportHelper.FileName = strReportFileName;
                Hashtable reportParams = new Hashtable();
                reportParams.Add("prARSaleReturnID", Toolbar.CurrentObjectID);
                reportParams.Add("prBRBranchID", THSApp.CurrentCompanyInfo.FK_BRBranchID);
                ReportHelper.DisplayReport(reportParams);
                ReportHelper.ReportDoc.PrintToPrinter(1, false, 1, 1);
            }
        }

        public void Staff_Validated(object sender, EventArgs e)
        {
            THSLookupEdit lke = (THSLookupEdit)sender;
            if (lke != null && lke.EditValue != lke.OldEditValue)
            {
                HREmployeesInfo objHREmployeesInfo = (HREmployeesInfo)new HREmployeesController().GetObjectByID(Convert.ToInt32(lke.EditValue));
                if (objHREmployeesInfo != null)
                {
                    ((ARSaleReturnsInfo)CurrentModuleEntity.MainObject).ARSaleReturnEmployeePicture = objHREmployeesInfo.HREmployeePicture;
                    CurrentModuleEntity.UpdateMainObjectBindingSource();
                }
            }
        }

        public void EditCustomer()
        {
            ARSaleReturnsInfo objARSaleReturnsInfo = (ARSaleReturnsInfo)CurrentModuleEntity.MainObject;
            Modules.Customer.CustomerModule customerModule = (Modules.Customer.CustomerModule)ParentScreen.ShowModule("Customer");
            for (int i = 0; i < customerModule.Toolbar.ObjectCollection.Tables[0].Rows.Count; i++)
                if (objARSaleReturnsInfo.FK_ARCustomerID == Convert.ToInt32(customerModule.Toolbar.ObjectCollection.Tables[0].Rows[i]["ARCustomerID"]))
                {
                    customerModule.Toolbar.CurrentIndex = i;
                    customerModule.FocusRowOfGridSearchResultByToolbarCurrentIndex();
                    customerModule.Invalidate(objARSaleReturnsInfo.FK_ARCustomerID);
                    customerModule.ActionEdit();
                    return;
                }
        }
        #endregion
    }
}
